package com.example.demo.service;

import com.example.demo.command.PublishBookCmd;
import com.example.demo.command.UpdatePriceCmd;
import com.example.demo.entity.BookEntity;
import com.example.demo.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Haibin Yuan
 */
@Service
public class BookService {

    @Autowired
    private BookRepository bookRepo;

    @Autowired
    private IsbnService publisherService;

    public BookEntity publish(PublishBookCmd command) {
        BookEntity entity = new BookEntity();
        entity.setAuthor(command.getAuthor());
        entity.setName(command.getName());
        entity.setPrice(command.getPrice());

        // generate unique ISBN for new book
        entity.setIsbn(publisherService.generateISBN());

        // set publish date
        entity.setPublishOn(new Date());

        return bookRepo.save(entity);
    }

    public List<BookEntity> findByAuthor(String author) {
        return bookRepo.findAllByAuthor(author);
    }

    public List<BookEntity> findAllBooks() {
        return bookRepo.findAll();
    }

    public void destroy(Long id) {
        bookRepo.deleteById(id);
    }

    public BookEntity updatePrice(UpdatePriceCmd command) {
        BookEntity entity = bookRepo.findById(command.getId()).get();
        entity.setPrice(command.getPrice());
        return bookRepo.save(entity);
    }

    public BookEntity findById(Long id) {
        return bookRepo.findById(id).get();
    }
}
